from PyQt4.QtCore import QVariant
from PyQt4.QtCore import Qt
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QAbstractItemView
from PyQt4.QtGui import QAction
from PyQt4.QtGui import QCursor
from PyQt4.QtGui import QHBoxLayout
from PyQt4.QtGui import QHeaderView
from PyQt4.QtGui import QMenu
from PyQt4.QtGui import QTableView
from PyQt4.QtGui import QWidget
from PyQt4.QtSql import QSqlTableModel


class NetworkRoom(QWidget):
    def __init__(self, phonik):
        #parent constructor
        QWidget.__init__(self)

        self.phonik = phonik
        self.mediaManager = phonik.mediaManager

        #gui
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setMargin(0)
        self.networkView = NetworkView()
        self.networkModel = NetworkModel(phonik)
        self.networkView.setModel(self.networkModel)
        self.horizontalLayout.addWidget(self.networkView)

        #setup gui
        self.networkView.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
        self.networkView.setColumnWidth(0, 500)


        self.signals()


    def urlSelected(self, index):
        url = str(index.sibling(index.row(), 1).data().toString().toUtf8())
        self.phonik.playUrls([url])


    def update(self):
        self.networkModel.select()
        

    def signals(self):
        self.connect(self.networkView, SIGNAL('clicked (const QModelIndex&)'), self.urlSelected)


class NetworkView(QTableView):
    def __init__(self):
        #parent constructor
        QTableView.__init__(self)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.verticalHeader().hide()
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.setShowGrid(False)
        self.setAcceptDrops(True)
        self.setDragDropMode(QAbstractItemView.DropOnly)

        self.connect(self, SIGNAL('customContextMenuRequested(const QPoint &)'), self.showContextMenu)


    def showContextMenu(self, pos):
        actionList = [QAction(self.tr('Remove'), self), QAction(self.tr('Rename'), self)]
        result = QMenu().exec_(actionList, QCursor.pos())
        if result:
            if result.text() == self.tr('Remove'):
                self.model().removeRow(self.indexAt(pos).row())
            elif result.text() == self.tr('Rename'):
                self.edit(self.indexAt(pos))
        


class NetworkModel(QSqlTableModel):
    def __init__(self, phonik):
        #parent constructor
        QSqlTableModel.__init__(self)

        self.phonik = phonik

        self.setTable('network')
        self.setHeaderData(0, Qt.Horizontal, QVariant(self.tr('A station name')))
        self.setHeaderData(1, Qt.Horizontal, QVariant('URL'))

    def supportedDropActions(self):
        return Qt.MoveAction | Qt.CopyAction

    def dropMimeData(self, data, action, row, column, parent):

        if action == Qt.IgnoreAction:
            return True

        if 'application/x-qabstractitemmodeldatalist' in data.formats():
            import pickle

            rowsPositions = pickle.loads(data.data("application/x-qabstractitemmodeldatalist"))

            for pos in rowsPositions:
                url = self.phonik.playList.model().table[pos][7]
                title = self.phonik.playList.model().table[pos][1]
                if 'http' in url:
		    if not title:
			title = self.tr('A station name')
                    self.phonik.query.exec_('insert into network values("' + title + '","' + url + '")')
                    self.phonik.networkRoom.update()
                    return False
                return False

        return False


    def mimeTypes(self):
        return ['application/x-qabstractitemmodeldatalist', 'text/uri-list']
    

    def flags(self, index):
        return Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable

